<template>
  <div>
    <pro-table
      ref="tableRef"
      row-key="id"
      :data="tableData"
      :total="total"
      :columns="columns"
      :tool-button="false"
      @search="commEvent.onSearch"
      :tree-props="{ children: 'childrenTree', hasChildren: 'hasChildren' }"
      :expand-row-keys="expandKeys"
    >
      <template #tableHeader>
        <el-row justify="end">
          <el-button type="primary" icon="Plus" @click="commEvent.onSave()">新增</el-button>
        </el-row>
      </template>
      <template #operation="{ row }">
        <template v-if="row.level !== 0">
          <el-button type="primary" link @click="commEvent.onSave(row)">编辑</el-button>
          <el-button type="danger" link @click="commEvent.onDelete(row)">删除</el-button>
        </template>
        <span v-else>--</span>
      </template>
    </pro-table>
    <!-- 新增/编辑弹窗 -->
    <save-organ v-model="saveVisible" :trees="tableData" :rows="currRow" @refresh="commEvent.onSearch" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"
import ProTable from "@/components/ProTable/index.vue"
import SaveOrgan from "./components/SaveOrgan.vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface"
import { organTree, deleteOrgan } from "@/api/modules/system"
import { SystemSpace } from "@/api/interface/system"
// 参数
const tableRef = ref<ProTableInstance>() // 表格实例
const tableData = ref<SystemSpace.OrganTree[]>([]) // 表格数据
const total = ref<number>(0) // 数据总数
const expandKeys = ref<string[]>([]) // 展开项
const saveVisible = ref<boolean>(false) // 新增/编辑弹窗
const currRow = ref<SystemSpace.OrganTree>() // 当前数据
// 表格列配置
const columns: ColumnProps<SystemSpace.OrganTree>[] = [
  { prop: "organName", label: "名称", align: "left" },
  { prop: "personCharge", label: "负责人" },
  { prop: "operation", label: "操作", width: 120, fixed: "right" }
]
// 事件集合
const commEvent = {
  // 获取表格数据
  getTableData: async (load?: boolean) => {
    const { data } = await organTree()
    tableData.value = data
    if (load) {
      expandKeys.value = data.map(item => item.id + "")
    }
  },
  // 查询
  onSearch: () => {
    commEvent.getTableData()
  },
  // 新增/编辑
  onSave: (row?: SystemSpace.OrganTree) => {
    currRow.value = row
    saveVisible.value = true
  },
  // 删除
  onDelete: (row: SystemSpace.OrganTree) => {
    ElMessageBox.confirm("确定删除此方案?", "删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        const { code } = await deleteOrgan({ id: row.id })
        if (code !== "200") return
        ElMessage.success("删除成功")
        commEvent.onSearch()
      })
      .catch(() => {})
  }
}
onMounted(() => {
  commEvent.getTableData(true)
})
</script>

<style lang="scss" scoped></style>
